from flask import Blueprint,request,make_response,jsonify,redirect
from flask_restful import Resource,Api
import json
from application.models.users.user import *
from application.models.users.user import db
from utils.comm import get_ali_object
from utils.Myjwt import myjwt
import functools,time
import requests
# from db import db
import random
vip_blue=Blueprint("vip_order",__name__)
api=Api(vip_blue)

# 购买vip生成订单
@vip_blue.route("/buy",methods=["POST"])
def buy():
    data=json.loads(request.data)
    userid=data["userid"]
    year=data["year"]
    money=200
    tmoney=money*int(year)
    # 生成订单号
    order_no=str(int(time.time()))+str(userid)+str(random.randint(100,999))
    # 写入vip记录表
    viprecord=VipRecord(order_no=order_no,userid=userid,year=year,money=tmoney,active_money=tmoney,status=1)
    db.session.add(viprecord)
    db.session.commit()
    # 支付 返回url
    pay=get_ali_object()
    # 生成支付的url # 生成支付的url 调用pay里面direct_pay去支付
    query_params = pay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    # 挂起支付（正在支付中）跳转之前 把订单号加入延时队列  回调成功再从callback中删除
    return jsonify({"code":200,"url":pay_url})

def updateorders(order_no,out_trade_no):
    # 加上事务处理 更新订单状态 订单表和用户表
    # 成功更新订单状态，更新用户类型，更新vip表
    # 更新订单表
    stime=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    order=Orders.query.filter(Orders.createtime==stime).first()
    order.status=2
    db.session.commit()
    # order_num=VipRecord.query.filter(VipRecord.order_no==)
@vip_blue.route("/callback")
def callback():
    order_no=request.args.get("out_trade_no")
    res=VipRecord.query.filter_by(order_no=order_no).first()
    uid=int(res.userid)
    year=res.year
    if int(year)==1:
        year=365
    elif int(year)==2:
        year=365*2
    stime=datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
    etime=datetime.datetime.now()+datetime.timedelta(days=year)
    etime=datetime.datetime.strftime(etime,"%Y-%m-%d %H:%M:%S")
    vip=Vip(userid=uid,s_time=stime,e_time=etime)
    db.session.add(vip)
    order=VipRecord.query.filter_by(order_no=order_no).first()
    order.status=2
    user=User.query.filter_by(id=uid).first()
    user.level=2
    db.session.commit()
    return redirect("http://localhost:8080/#/vip")
